package service

import (
	"fmt"
	"gitee.com/gitee-go/core"
	"gitee.com/gitee-go/core/model/pipeline"
	"gitee.com/gitee-go/server/comm"
	"gitee.com/gitee-go/utils"
	"github.com/gin-gonic/gin"
	"strconv"
)

// 通过ID获取用户
func GetUser(uid int64) (*pipeline.TUser, bool) {
	e := &pipeline.TUser{}
	ok, err := comm.DBMain.GetDB().Where("id=?", uid).Get(e)
	if err != nil {
		core.Log.Errorf("GetUser(%s) err:%v", uid, err)
	}
	return e, ok
}

// 通过用户名获取用户
func FindUserName(name string) (*pipeline.TUser, bool) {
	e := &pipeline.TUser{}
	ok, err := comm.DBMain.GetDB().Where("name=?", name).Get(e)
	if err != nil {
		core.Log.Errorf("FindUserName(%s) err:%v", name, err)
	}
	return e, ok
}

// 获取用户并缓存,减少数据库压力
func GetUserCache(uid int64) (*pipeline.TUser, bool) {
	var ok bool
	e := &pipeline.TUser{}
	uids := fmt.Sprintf("user:%d", uid)
	err := comm.CacheGets(uids, e)
	if err == nil {
		return e, true
	}
	e, ok = GetUser(uid)
	if ok {
		comm.CacheSets(uids, e)
	}
	return e, ok
}

// 从request获取当前用户,如果未登录返回nil
func CurrUserCache(c *gin.Context) (*pipeline.TUser, bool) {
	defer func() {
		if err := recover(); err != nil {
			return
		}
	}()
	tk := utils.GetToken(c, comm.MainCfg.ServerConf.LoginKey)
	if tk == nil {
		return nil, false
	}
	uid, ok := tk["uid"]
	if !ok {
		return nil, false
	}
	uids, ok := uid.(string)
	if !ok {
		return nil, false
	}
	uidi, err := strconv.ParseInt(uids, 10, 64)
	if err != nil {
		return nil, false
	}
	return GetUserCache(uidi)
}
